package com.bwie.filter;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

/**
 * @author 军哥
 * @version 1.0
 * @description: 网关全局过滤器
 * @date 2025/5/22 10:18
 */

@Configuration
@Order(1)
public class MyGlobalFilter implements GlobalFilter {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //--1 获取参数
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();
        String url = request.getURI().getPath();
        System.out.println("url:" + url);

        //--2 白名单:登录、注册、获取验证码、获取图形验证码
        if(url.contains("/login")) {
            System.out.println("白名单：" + url);
            return chain.filter(exchange);
        }

        //--3 获取并校验token
        String token = request.getHeaders().getFirst("token");
        if(token == null) {
            System.out.println("token为空:" + url);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer userId = body.get("userId", Integer.class);
        String key = "token-" + userId;
        String redisToken = stringRedisTemplate.opsForValue().get(key);
        if(redisToken == null) {
            System.out.println("token已过期:" + url);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        if(!token.equals(redisToken)) {
            System.out.println("token错误:" + url);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //--4 token续期(续期60分钟)
        stringRedisTemplate.expire(key, 60, TimeUnit.MINUTES);

        //--5 放行（转发）
        System.out.println("放行:" + url);
        return chain.filter(exchange);
    }
}
